//
//  YAYIThisMonthViewController.m
//  YAYIDoctor
//
//  Created by Veer on 16/5/9.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIThisMonthViewController.h"
#import "YAYIPerformanceLineChart.h"
#import "YAYIPerformanceDetailViewController.h"


@interface YAYIThisMonthViewController ()

@property (nonatomic, weak) UIScrollView *scrollView;

@property (nonatomic, weak) UIView *topView;
@property (nonatomic, weak) UILabel *dateLblLbl;
@property (nonatomic, weak) UILabel *performanceLbl;

@property (nonatomic, weak) UIView *centerView;
@property (nonatomic, weak) UILabel *serviceCountLbl;

@property (nonatomic, weak) UIView *bottomView;
@property (nonatomic, weak) YAYIPerformanceLineChart *lineChart0;
@property (nonatomic, weak) YAYIPerformanceLineChart *lineChart1;


/** 数据总数 */
@property (nonatomic, assign) NSInteger serviceCount;
@property (nonatomic, assign) CGFloat totalPerformance;


@end

@implementation YAYIThisMonthViewController{
    // 用于数字增长动画
    NSInteger index;
    NSInteger kMaxTimes;
    CGFloat value;
    CGFloat stepValue;
}


- (void)setServiceCount:(NSInteger)serviceCount
{
    _serviceCount = serviceCount;
    self.serviceCountLbl.text = [NSString stringWithFormat:@"%ld", serviceCount];
}

- (void)setTotalPerformance:(CGFloat)totalPerformance
{
    _totalPerformance = totalPerformance;
    
    kMaxTimes = 50;
    stepValue = totalPerformance / kMaxTimes;
    
    //    self.performanceLbl.text = [self thousandsSeparatorWith:totalPerformance];
    [self changeNumberBySelector];
}


- (void)changeNumberBySelector {
    if (index >= kMaxTimes) {
        self.performanceLbl.text = [self thousandsSeparatorWith:self.totalPerformance];
        return;
    } else {
        index++;
        value += stepValue;
        self.performanceLbl.text = [self thousandsSeparatorWith:value];
        [self performSelector:@selector(changeNumberBySelector) withObject:nil afterDelay:0.02];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    //    scrollView.backgroundColor = [UIColor yellowColor];
    
    scrollView.frame = CGRectMake(0, 100, SCREEN_width, SCREEN_height - 64 - 40 - 100);
    //    self.scrollView.height = SCREEN_height - 64 - 40;
    scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    
    YAYILog(@"self.view.frame:%@", NSStringFromCGRect(self.scrollView.frame));
    
    [self setupTopView];
    [self setupCenterView];
    [self setupBottomView];
    
//    [self getPerformance];
}


- (void)setupTopView
{

    UIView *topView = [[UIView alloc] init];
    [self.view addSubview:topView];
    self.topView = topView;
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.view);
        make.width.equalTo(@(SCREEN_width));
        make.height.equalTo(@100);
    }];
    
    
    NSDate *curDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM  本月实际业绩";
    NSString *dateStr = [formatter stringFromDate:curDate];
    
    // 日期
    NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:dateStr];
    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, 2)];
    
    UILabel *dateLbl = [[UILabel alloc] init];
    dateLbl.font = [UIFont systemFontOfSize:14];
    dateLbl.textColor = [UIColor whiteColor];
    dateLbl.text = dateStr;
    [topView addSubview:dateLbl];
    [dateLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.top.equalTo(@15);
    }];
    
    // 业绩
    UILabel *performanceLbl = [[UILabel alloc] init];
    performanceLbl.text = @"0.00";
    performanceLbl.textAlignment = NSTextAlignmentCenter;
    performanceLbl.font = [UIFont systemFontOfSize:26];
    performanceLbl.textColor = [UIColor whiteColor];
    [topView addSubview:performanceLbl];
    self.performanceLbl = performanceLbl;
    [performanceLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-40);
        make.centerY.equalTo(topView).offset(10);
    }];
    
    // 线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = YAYIColor(0xdd, 0xdd, 0xdd);
    [topView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@0.5);
        make.left.right.equalTo(topView);
        make.bottom.equalTo(topView);
    }];
    
}


- (void)setupCenterView
{
    UIButton *centerView = [UIButton buttonWithType:UIButtonTypeSystem];
    centerView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:centerView];
    [centerView addTarget:self action:@selector(servieceCountAction:) forControlEvents:UIControlEventTouchUpInside];
    self.centerView = centerView;
    [centerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView).offset(0);
        make.left.equalTo(self.scrollView);
        make.width.equalTo(@(SCREEN_width));
        make.height.equalTo(@44);
    }];
    
    
    // 线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = YAYIColor(0xdd, 0xdd, 0xdd);
    [centerView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@0.5);
        make.left.right.equalTo(centerView);
        make.top.equalTo(centerView);
    }];
    
    //title
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"本月服务患者人次";
    titleLbl.font = [UIFont systemFontOfSize:16];
    titleLbl.textColor = YAYIColor(80, 80, 80);
    [centerView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.width.equalTo(@200);
        make.centerY.equalTo(centerView);
    }];
    
    // 服务人次
    UILabel *detailLbl = [[UILabel alloc] init];
    detailLbl.font = [UIFont systemFontOfSize:16];
    detailLbl.textColor = YAYIColor(80, 80, 80);
    detailLbl.textAlignment = NSTextAlignmentRight;
    [centerView addSubview:detailLbl];
    self.serviceCountLbl = detailLbl;
    [detailLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-30);
        make.centerY.equalTo(centerView);
    }];
    
    UIImageView *accessIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"accessIcon"]];
    [centerView addSubview:accessIcon];
    [accessIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@7);
        make.height.equalTo(@12);
        make.right.equalTo(@-15);
        make.centerY.equalTo(centerView);
    }];
    
    UIView *bottomLineView = [[UIView alloc] init];
    bottomLineView.backgroundColor = YAYIColor(0xdd, 0xdd, 0xdd);
    [centerView addSubview:bottomLineView];
    [bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@0.5);
        make.left.right.equalTo(centerView);
        make.bottom.equalTo(centerView);
    }];
}


- (void)setupBottomView
{
    CGFloat bottomViewH = 30 + 170 + 10 + 30 + 170 + 10;
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.centerView.mas_bottom);
        make.left.equalTo(@0);
        make.width.equalTo(@(SCREEN_width));
        make.height.equalTo(@(bottomViewH));
    }];
    
    UILabel *titelLbl0 = [[UILabel alloc] init];
    titelLbl0.text = @"实际业绩（元）";
    titelLbl0.font = [UIFont systemFontOfSize:15];
    [bottomView addSubview:titelLbl0];
    [titelLbl0 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@30);
        make.left.equalTo(@20);
        make.top.equalTo(@0);
    }];
    
    // 获取当月天数
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    // 实际业绩
    YAYIPerformanceLineChart *lineChart0 = [[YAYIPerformanceLineChart alloc] init];
    lineChart0.chartType = ChartTypeThisMonth;
    
    NSString *lastDayStr = [NSString stringWithFormat:@"%ld日", numberOfDaysInMonth];
    lineChart0.xArray = @[@"1日", @"", @"", @"", @"", @"", lastDayStr];
    
    [bottomView addSubview:lineChart0];
    self.lineChart0 = lineChart0;
    [lineChart0 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@30);
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
        make.height.equalTo(@170);
    }];
    
    
    // 服务患者
    UILabel *titelLbl1 = [[UILabel alloc] init];
    titelLbl1.text = @"服务患者（人次）";
    titelLbl1.font = [UIFont systemFontOfSize:15];
    [bottomView addSubview:titelLbl1];
    [titelLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@30);
        make.left.equalTo(@20);
        make.top.equalTo(lineChart0.mas_bottom).offset(10);
    }];
    
    YAYIPerformanceLineChart *lineChart1 = [[YAYIPerformanceLineChart alloc] init];
    lineChart1.xArray = @[@"1日", @"", @"", @"", @"", @"", lastDayStr];;
    lineChart1.dataType = DataTypeServiceCount;
    lineChart1.chartType = ChartTypeThisMonth;
    [bottomView addSubview:lineChart1];
    self.lineChart1 = lineChart1;
    [lineChart1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineChart0.mas_bottom).offset(10 + 30);
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
        make.height.equalTo(@170);
    }];
    
    // 设置scrollview的contentOffset
    CGFloat scrollViewContentOffsetY = 10 + 44 + bottomViewH;
    self.scrollView.contentSize = CGSizeMake(SCREEN_width, scrollViewContentOffsetY);
}


#pragma mark - 点击事件
- (void)servieceCountAction:(UIButton *)sender
{
    YAYIPerformanceDetailViewController *detailVc = [[YAYIPerformanceDetailViewController alloc] init];
    detailVc.typeStr = @"m";
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 工具方法
/** 数组分 */
- (NSString *)thousandsSeparatorWith:(CGFloat)number
{
    NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
//    [numberFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4];
//    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *numberStr = [numberFormatter stringFromNumber: [NSNumber numberWithDouble:number]];
    
    return [NSString stringWithFormat:@"%@", numberStr];
}

#pragma mark - 获取数据
- (void)getPerformance
{
    // 显示hud
    //    [SVProgressHUD show];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"type"] = @"m";
    
    [YAYINetWorking getWithURL:me_performance param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                
                // 实际业绩
                NSArray *performanceArray = dict[@"data"][@"performance"];
                NSMutableArray *performanceModelArray = [NSMutableArray array];
                CGFloat totalPrice = 0;
                NSInteger serviceCount = 0;
                for (NSDictionary *dict in performanceArray) {
                    YAYIPerformanceModel *model = [[YAYIPerformanceModel alloc] init];
                    [model setValuesForKeysWithDictionary:dict];
                    model.starttime = [dict[@"paytime"] integerValue];
                    
                    [performanceModelArray addObject:model];
                    totalPrice += model.totalprice;
                }
                
                // 服务患者人次
                NSArray *serviceArray = dict[@"data"][@"serviceMans"];
                NSMutableArray *serviceModelArray = [NSMutableArray array];
                for (NSDictionary *dict in serviceArray) {
                    YAYIPerformanceModel *model = [[YAYIPerformanceModel alloc] init];
                    [model setValuesForKeysWithDictionary:dict];
                    
                    [serviceModelArray addObject:model];
                    serviceCount += model.servieNum;
                }
                
                self.totalPerformance = totalPrice / 100.0;
                self.serviceCount = serviceCount;
                
                self.lineChart0.dataArray = performanceModelArray;
                self.lineChart1.dataArray = serviceModelArray;
            }
            
        }else{
            
            YAYILog(@"erro:%@", error);
        }
        
        // 取消显示hud
        //        [SVProgressHUD dismiss];
    }];
}


@end
